package com.cs342.uwosh.cloudycontacts.tasks.network;

import java.io.InputStream;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.cs342.uwosh.cloudycontacts.LoginActivity;
import com.cs342.uwosh.cloudycontacts.MainActivity;
import com.cs342.uwosh.cloudycontacts.RestClient;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetUserDetailsTask;

import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class AttemptRegistrationForCloudSpaceTask extends AsyncTask<String, String, Boolean>
{

	public int iLanguage = 0;
	Typeface arabicFont = null;
	int TIMEOUT_MILLISEC = 10000; // = 10 seconds
	
	@Override
	protected Boolean doInBackground(String... params)
	{
		/*
		 * This task takes in two strings:
		 * 1) A user name which we call email in the GUI and in XML code
		 * 2) A password
		 * These strings will be posted out to a web service which will check if they exist
		 * True is returned if the user name does not already exist in the database
		 * False is returned otherwise
		 */
		
		String postResponse = "";
		try
		{
			JSONObject json = new JSONObject();
			json.put("user_name", params[0]);
			json.put("password", params[1]);
			
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			
			//String url = "http://10.0.2.2:8080/sample1/webservice2.php?json={\"UserName\":1,\"FullName\":2}";
			String url = "http://softeng.cs.uwosh.edu/students/kiserj66/Web/sign_up.php";
			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				
				String result = RestClient.convertStreamToString(instream);
				Log.i("Read from server", result);

				postResponse = result;
			}
		}
		catch (Throwable t)
		{
			postResponse = "Request failed: " + t.toString();
		}
		if (postResponse.equals("fail\n"))
		{
			return false;
		}
		else
		{
			MainActivity.db.createUser(new String [] {params[0],params[1]},Integer.parseInt(postResponse.substring(0, postResponse.length()-1)));
			return true;
		}
	}
	
	
	@Override
	protected void onPostExecute(Boolean result)
	{
		if(result)
		{
			String[] userDetails = new String[] {"",""};
			try {
				userDetails = new GetUserDetailsTask().execute().get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			new PostToCloudTask().execute(userDetails[0],userDetails[1]);
			Toast.makeText(LoginActivity.mainC, "Hi", Toast.LENGTH_LONG);
		}
	}
}
